package org.mat.ipaas.ucenter.service.modules.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.biz.common.constant.CacheConstant;
import org.mat.ipaas.ucenter.biz.common.system.query.QueryGenerator;
import org.mat.ipaas.ucenter.biz.modules.system.entity.SysDictItem;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysDictItemService;
import org.mat.ipaas.ucenter.service.api.system.SysDictItemRestAPI;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysDictItemDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @Author zhangweijian
 * @since 2018-12-28
 */
@Api(tags = "数据字典")
@RestController
@RequestMapping("/sys/dictItem")
@Slf4j
public class SysDictItemController implements SysDictItemRestAPI {

    @Autowired
    private ISysDictItemService sysDictItemService;

    /**
     * @param sysDictItemDTO
     * @param pageNo
     * @param pageSize
     * @return
     * @功能：查询字典数据
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public MatApiResponse<Page<SysDictItemDTO>> queryPageList(@SpringQueryMap SysDictItemDTO sysDictItemDTO,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        MatApiResponse<Page<SysDictItemDTO>> matApiResponse = new MatApiResponse<>();
        SysDictItem sysDictItem = toSysDictItem(sysDictItemDTO);

        QueryWrapper<SysDictItem> queryWrapper = QueryGenerator.initQueryWrapper(sysDictItem, request.getParameterMap());
        queryWrapper.orderByAsc("sort_order");
        Page<SysDictItem> page = new Page<SysDictItem>(pageNo, pageSize);
        IPage<SysDictItem> pageList = sysDictItemService.page(page, queryWrapper);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysDictItemDTOPage(pageList));
        return matApiResponse;
    }

    /**
     * @return
     * @功能：新增
     */
    //@RequiresPermissions("system:dict:item:add")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @CacheEvict(value = {CacheConstant.SYS_DICT_CACHE, CacheConstant.SYS_ENABLE_DICT_CACHE}, allEntries = true)
    public MatApiResponse<SysDictItemDTO> add(@RequestBody SysDictItemDTO sysDictItemDTO) {
        MatApiResponse<SysDictItemDTO> matApiResponse = new MatApiResponse<>();
        SysDictItem sysDictItem = toSysDictItem(sysDictItemDTO);

        try {
            sysDictItem.setCreateTime(new Date());
            sysDictItemService.save(sysDictItem);
            matApiResponse.success("保存成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("操作失败");
        }
        return matApiResponse;
    }

    /**
     * @param sysDictItemDTO
     * @return
     * @功能：编辑
     */
    //@RequiresPermissions("system:dict:item:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    @CacheEvict(value = {CacheConstant.SYS_DICT_CACHE, CacheConstant.SYS_ENABLE_DICT_CACHE}, allEntries = true)
    public MatApiResponse<SysDictItemDTO> edit(@RequestBody SysDictItemDTO sysDictItemDTO) {
        MatApiResponse<SysDictItemDTO> matApiResponse = new MatApiResponse<>();
        SysDictItem sysDictItem = toSysDictItem(sysDictItemDTO);
        SysDictItem sysdict = sysDictItemService.getById(sysDictItem.getId());
        if (sysdict == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            sysDictItem.setUpdateTime(new Date());
            boolean ok = sysDictItemService.updateById(sysDictItem);
            //TODO 返回false说明什么？
            if (ok) {
                matApiResponse.success("编辑成功!");
            }
        }
        return matApiResponse;
    }

    /**
     * @param id
     * @return
     * @功能：删除字典数据
     */
    //@RequiresPermissions("system:dict:item:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    @CacheEvict(value = {CacheConstant.SYS_DICT_CACHE, CacheConstant.SYS_ENABLE_DICT_CACHE}, allEntries = true)
    public MatApiResponse<SysDictItemDTO> delete(@RequestParam(name = "id", required = true) String id) {
        MatApiResponse<SysDictItemDTO> matApiResponse = new MatApiResponse<>();
        SysDictItem joinSystem = sysDictItemService.getById(id);
        if (joinSystem == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            boolean ok = sysDictItemService.removeById(id);
            if (ok) {
                matApiResponse.success("删除成功!");
            }
        }
        return matApiResponse;
    }

    /**
     * @param ids
     * @return
     * @功能：批量删除字典数据
     */
    //@RequiresPermissions("system:dict:item:deleteBatch")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    @CacheEvict(value = {CacheConstant.SYS_DICT_CACHE, CacheConstant.SYS_ENABLE_DICT_CACHE}, allEntries = true)
    public MatApiResponse<SysDictItemDTO> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        MatApiResponse<SysDictItemDTO> matApiResponse = new MatApiResponse<>();
        if (ids == null || "".equals(ids.trim())) {
            matApiResponse.fail("参数不识别！");
        } else {
            this.sysDictItemService.removeByIds(Arrays.asList(ids.split(",")));
            matApiResponse.success("删除成功!");
        }
        return matApiResponse;
    }

    /**
     * 字典值重复校验
     *
     * @param sysDictItemDTO
     * @return
     */
    @RequestMapping(value = "/dictItemCheck", method = RequestMethod.GET)
    @ApiOperation("字典重复校验接口")
    public MatApiResponse<Object> doDictItemCheck(@SpringQueryMap SysDictItemDTO sysDictItemDTO) {
        SysDictItem sysDictItem = toSysDictItem(sysDictItemDTO);
        Long num = Long.valueOf(0);
        LambdaQueryWrapper<SysDictItem> queryWrapper = new LambdaQueryWrapper<SysDictItem>();
        queryWrapper.eq(SysDictItem::getItemValue, sysDictItem.getItemValue());
        queryWrapper.eq(SysDictItem::getDictId, sysDictItem.getDictId());
        if (StringUtils.isNotBlank(sysDictItem.getId())) {
            // 编辑页面校验
            queryWrapper.ne(SysDictItem::getId, sysDictItem.getId());
        }
        num = sysDictItemService.count(queryWrapper);
        if (num == 0) {
            // 该值可用
            return MatApiResponse.success("该值可用！");
        } else {
            // 该值不可用
            log.info("该值不可用，系统中已存在！");
            return MatApiResponse.fail("该值不可用，系统中已存在！");
        }
    }


    private Page<SysDictItemDTO> toSysDictItemDTOPage(IPage<SysDictItem> pageList) {
        Page<SysDictItemDTO> sysDictItemDTOPage = new Page<>();
        List<SysDictItemDTO> sysDictItemDTOList = new ArrayList<>();
        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (SysDictItem sysDictItem : pageList.getRecords()) {
                sysDictItemDTOList.add(toSysDictItemDTO(sysDictItem));
            }
        }

        sysDictItemDTOPage.setSize(pageList.getSize());
        sysDictItemDTOPage.setCurrent(pageList.getCurrent());
        sysDictItemDTOPage.setTotal(pageList.getTotal());
        sysDictItemDTOPage.setRecords(sysDictItemDTOList);
        return sysDictItemDTOPage;
    }

    private SysDictItemDTO toSysDictItemDTO(SysDictItem sysDictItem) {
        if (sysDictItem == null) {
            return null;
        }
        SysDictItemDTO sysDictItemDTO = new SysDictItemDTO();
        sysDictItemDTO.setId(sysDictItem.getId());
        sysDictItemDTO.setDictId(sysDictItem.getDictId());
        sysDictItemDTO.setItemText(sysDictItem.getItemText());
        sysDictItemDTO.setItemValue(sysDictItem.getItemValue());
        sysDictItemDTO.setDescription(sysDictItem.getDescription());
        sysDictItemDTO.setSortOrder(sysDictItem.getSortOrder());
        sysDictItemDTO.setStatus(sysDictItem.getStatus());
        sysDictItemDTO.setCreateBy(sysDictItem.getCreateBy());
        sysDictItemDTO.setCreateTime(sysDictItem.getCreateTime());
        sysDictItemDTO.setUpdateBy(sysDictItem.getUpdateBy());
        sysDictItemDTO.setUpdateTime(sysDictItem.getUpdateTime());
        return sysDictItemDTO;
    }

    private SysDictItem toSysDictItem(SysDictItemDTO sysDictItemDTO) {
        if (sysDictItemDTO == null) {
            return null;
        }
        SysDictItem sysDictItem = new SysDictItem();
        sysDictItem.setId(sysDictItemDTO.getId());
        sysDictItem.setDictId(sysDictItemDTO.getDictId());
        sysDictItem.setItemText(sysDictItemDTO.getItemText());
        sysDictItem.setItemValue(sysDictItemDTO.getItemValue());
        sysDictItem.setDescription(sysDictItemDTO.getDescription());
        sysDictItem.setSortOrder(sysDictItemDTO.getSortOrder());
        sysDictItem.setStatus(sysDictItemDTO.getStatus());
        sysDictItem.setCreateBy(sysDictItemDTO.getCreateBy());
        sysDictItem.setCreateTime(sysDictItemDTO.getCreateTime());
        sysDictItem.setUpdateBy(sysDictItemDTO.getUpdateBy());
        sysDictItem.setUpdateTime(sysDictItemDTO.getUpdateTime());
        return sysDictItem;
    }


}
